package site.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import neoutil.CommonEntity;
import neoutil.CommonService;
import neoutil.Config;
import neoutil.DaoSupport;
import neoutil.Page;

import org.apache.commons.dbutils.DbUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.rain.acm.Sso;

import site.dao.ResourceDao;
import site.dao.ReviewDAO;
import site.entity.Resource;
import site.entity.Review;
import site.helper.CommonHelper;
import site.helper.CourseTitle;
import site.helper.ResourceType;

/**
 * Description: 用户Resource的各种存储相关操作。
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午03:48:12
 */
public class ResourceRepository extends CommonService {
	private static Logger log = Logger.getLogger(ResourceRepository.class);

	/*
	 * public static void main(String[] args) { Connection connection = null;
	 * 
	 * try { connection = DaoSupport.getConnection(); ResourceDao resourceDao =
	 * new ResourceDao(connection);
	 * System.out.println(String.format("%1$03d%2$02d%3$S%4$06d", new
	 * Object[]{35,1,"SJ",resourceDao.getMaxId("resource")})); } catch
	 * (Exception e) { e.printStackTrace(); } finally {
	 * closeConnection(connection); } }
	 */

	public Resource getResourceByUuid(String uuid) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			return resourceDao.getByUuid(uuid);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Resource findById(int i) {

		Connection connection = DaoSupport.getConnection();
		ResourceDao rd = new ResourceDao(connection);
		Resource resource = null;
		try {
			resource = rd.getById((long) i);
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return resource;
	}

	public Resource getByNormcode(String normcode) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			return resourceDao.getByNormcode(normcode);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public List<Resource> getByDate(Date date) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			return resourceDao.getByDate(date);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public String save(Resource resource) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);

			if (CommonHelper.IsNullOrEmpty(resource.getNormcode())) {
				long maxId = resourceDao.getMaxId("resource");
				resource.setNormcode(String.format("%1$03d%2$S%3$S%4$06d", new Object[] { Integer.parseInt(Config.getTeamCode()), CourseTitle.ToCode(resource.getCourse()), ResourceType.ToCode(resource.getType()), maxId }));
			}

			resourceDao.save(resource);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存Resource对象出现异常！！");
			System.err.println(e);
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String updateResource(Resource resource) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			resourceDao.update(resource);
			return SUCCESS;
		} catch (Exception e) {
			log.error("更新Resource对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String deleteResourceByUuid(String uuid) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			Resource resource = resourceDao.getByUuid(uuid);
			resource.setEntityStatus(CommonEntity.ENTITY_STATUS_DELETED);
			resourceDao.update(resource);
			SynsResource(resource, "delete");
			return SUCCESS;
		} catch (Exception e) {
			log.error("删除Resource对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public Page<Resource> search(Page<Resource> page, String query) {
		Connection connection = DaoSupport.getConnection();
		ResourceDao ResourceDao = new ResourceDao(connection);

		try {
			Page<Resource> Resources = ResourceDao.find(page, "SELECT * FROM Resource WHERE entityStatus=1 and title like '%" + query + "%' ORDER BY chapter ASC");
			return Resources;
		} catch (Exception e) {
			log.error("搜索Resource对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @method getResourcesByCid
	 * @info author:陈亚鹏 date:2012-9-20 下午01:24:09 version:1.0
	 * @param page
	 * @param cid
	 * @param level
	 *            -1-所有，1-通过二审，2-通过三审，3-未通过
	 * @return Page<Resource>
	 */
	public Page<Resource> getResourcesByCid(Page<Resource> page, int cid, int level) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			String sql = "SELECT * FROM resource WHERE cid = ? AND entityStatus = " + CommonEntity.ENTITY_STATUS_NORMAL + " AND status>='" + level + "' ORDER BY chapter ASC";
			return resourceDao.find(page, sql, new Object[] { cid });
		} catch (Exception e) {
			log.error("获取被举报的Resource对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Resource> getResourcesByCidAndAuthor(Page<Resource> page, int cid, String author) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			String sql = "SELECT * FROM resource WHERE cid = ? AND author = ? AND entityStatus = " + CommonEntity.ENTITY_STATUS_NORMAL + " ORDER BY chapter DESC";
			return resourceDao.find(page, sql, new Object[] { cid, author });
		} catch (Exception e) {
			log.error("获取被举报的Resource对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public List<Resource> getLatestResourcesByCid(int cid, int num) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ResourceDao resourceDao = new ResourceDao(connection);
			String sql = "SELECT * FROM resource WHERE cid = ? AND entityStatus = " + CommonEntity.ENTITY_STATUS_NORMAL + " AND status = " + Resource.STATUS_THREEPASS + " ORDER BY publicTime DESC, chapter ASC limit 0, ?";
			return resourceDao.find(sql, new Object[] { cid, num });
		} catch (Exception e) {
			log.error("获取被举报的Resource对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public void SynsResource(Resource resource, String type) throws IOException {
		if (resource == null)
			return;
		List<NameValuePair> nvps = new LinkedList<NameValuePair>();
		nvps.add(new BasicNameValuePair("reses.title", resource.getTitle()));
		nvps.add(new BasicNameValuePair("reses.normCode", "S" + resource.getNormcode()));
		nvps.add(new BasicNameValuePair("reses.url", Config.getHostURL() + "resource/viewResourceByUuid.action?uuid=" + resource.getUuid()));
		nvps.add(new BasicNameValuePair("reses.format", resource.getFormat()));
		nvps.add(new BasicNameValuePair("reses.course", resource.getCourse()));

		String chapter = resource.getChapter();
		if (!CommonHelper.IsNullOrEmpty(chapter)) {
			chapter = chapter.replace("C", "");
		}
		nvps.add(new BasicNameValuePair("reses.chapter", chapter));
		String chapters = resource.getChapter();
		if (!CommonHelper.IsNullOrEmpty(chapters)) {
			chapters = chapters.replace("C", "");
		}
		nvps.add(new BasicNameValuePair("reses.chapters", chapters));
		nvps.add(new BasicNameValuePair("reses.author", resource.getAuthor()));
		nvps.add(new BasicNameValuePair("reses.authorRealName", resource.getAuthorRealName()));
		nvps.add(new BasicNameValuePair("reses.partners", resource.getPartners()));
		nvps.add(new BasicNameValuePair("reses.teamCode", resource.getTeamCode()));
		nvps.add(new BasicNameValuePair("reses.provider", "北京科技大学"));// resource.getProvider()));
		nvps.add(new BasicNameValuePair("reses.keywords", resource.getKeywords()));
		nvps.add(new BasicNameValuePair("reses.note", resource.getNote()));

		String FileURL = Config.getResourceSavePath() + "\\" + resource.getFileName();
		File file = new File(FileURL);
		if (file.exists()) {
			FileInputStream f = new FileInputStream(FileURL);
			long s = f.available();
			nvps.add(new BasicNameValuePair("reses.fileSize", s + ""));

			String extension = "";
			int dot = FileURL.lastIndexOf('.');
			if ((dot > -1) && (dot < (FileURL.length() - 1))) {
				extension = FileURL.substring(dot + 1);
			}
			nvps.add(new BasicNameValuePair("reses.fileName", resource.getTitle() + "." + extension));
		} else {
			nvps.add(new BasicNameValuePair("reses.fileSize", "0"));
			nvps.add(new BasicNameValuePair("reses.fileName", "无文件"));
		}

		nvps.add(new BasicNameValuePair("reses.fileCode", resource.getUuid()));
		nvps.add(new BasicNameValuePair("reses.publicTime", resource.getPublicTime().getTime() + ""));
		nvps.add(new BasicNameValuePair("reses.createTime", resource.getCreateTime().getTime() + ""));
		// nvps.add(new BasicNameValuePair("reses.relate",);
		// nvps.add(new BasicNameValuePair("reses.downloads",);
		nvps.add(new BasicNameValuePair("reses.recommends", resource.getVisitNum() + ""));
		nvps.add(new BasicNameValuePair("reses.type", resource.getType()));
		nvps.add(new BasicNameValuePair("updateType", type));
		log.info(Sso.post("http://www.sxz.edu.cn/szcr/reses/resSyn.htm", nvps));
	}
}
